package com.fzu.geometa.validate;

import com.fzu.geometa.validate.service.ValidateServiceImpl;
import io.grpc.Server;
import io.grpc.ServerBuilder;

import java.io.IOException;

public class ValidateRpcServer {
    private final int port;
    private final Server server;

    public ValidateRpcServer(int port) {
        this.port = port;
        this.server = ServerBuilder.forPort(port)
                .addService(new ValidateServiceImpl())
                .build();
    }

    public void start() throws IOException {
        server.start();
        System.out.println("RPC server started, listening on " + port);
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                System.err.println("*** shutting down gRPC server since JVM is shutting down");
                ValidateRpcServer.this.stop();
                System.err.println("*** server shut down");
            }
        });
    }

    public void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    public void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }
}
